<?php
/**
 * @copyright Copyright (c) 2021 深圳市酷瓜软件有限公司
 * @license https://opensource.org/licenses/GPL-2.0
 * @link https://www.koogua.com
 */

namespace App\Repos;

use App\Library\Paginator\Adapter\QueryBuilder as PagerQueryBuilder;
use App\Models\Article as ArticleModel;
use App\Models\ArticleFavorite as ArticleFavoriteModel;
use App\Models\ArticleLike as ArticleLikeModel;
use App\Models\ArticleTag as ArticleTagModel;
use App\Models\Comment as CommentModel;
use App\Models\Tag as TagModel;
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Resultset;
use Phalcon\Mvc\Model\ResultsetInterface;

class Agency extends Repository
{

    public function paginate($where = [], $sort = 'latest', $page = 1, $limit = 15)
    {
        $builder = $this->modelsManager->createBuilder();

        $builder->from(\App\Models\Agency::class);

        $builder->where('1 = 1');


        if (!empty($where['id'])) {
            if (is_array($where['id'])) {
                $builder->inWhere('id', $where['id']);
            } else {
                $builder->andWhere('id = :id:', ['id' => $where['id']]);
            }
        }

        if (!empty($where['title'])) {
            $builder->andWhere('title LIKE :title:', ['title' => "%{$where['title']}%"]);
        }


        if (isset($where['deleted'])) {
            $builder->andWhere('deleted = :deleted:', ['deleted' => $where['deleted']]);
        }

        $builder->orderBy('id DESC');

        $pager = new PagerQueryBuilder([
            'builder' => $builder,
            'page'    => $page,
            'limit'   => $limit,
        ]);

        return $pager->paginate();
    }

    /**
     * @param int $id
     * @return ArticleModel|Model|bool
     */
    public function findById($id)
    {
        return \App\Models\Agency::findFirst([
            'conditions' => 'id = :id:',
            'bind'       => ['id' => $id],
        ]);
    }

    public function findAgencies()
    {
        return \App\Models\Agency::query()
            ->columns('*')
            ->andWhere("deleted = :deleted:", ['deleted' => '0'])
            ->execute();
    }

    /**
     * @param array $ids
     * @param array|string $columns
     * @return ResultsetInterface|Resultset|ArticleModel[]
     */
    public function findByIds($ids, $columns = '*')
    {
        return \App\Models\Agency::query()
            ->columns($columns)
            ->inWhere('id', $ids)
            ->execute();
    }


    /**
     * @return ArticleModel|Model|bool
     */
    public function getRecommendAgency()
    {
        return \App\Models\Agency::query()
            ->where("to_index=:to_index:", ["to_index" => 1])
            ->execute();
    }

}
